class NoteManager {
    constructor() {
        this.storage = new StorageManager();
        this.currentCategoryId = 'all';
        this.expandedCategories = new Set(); // 存储展开的分类ID
        this.currentCategoryPath = []; // 存储当前分类的完整路径
        this.draggedNoteId = null;
    }

    // 初始化事件监听
    init() {
        // 分类相关
        document.getElementById('addCategory').addEventListener('click', () => this.createCategory());
        document.getElementById('categoryList').addEventListener('click', (e) => {
            const target = e.target;
            
            // 处理展开/折叠点击
            if (target.closest('.category-toggle')) {
                e.stopPropagation();
                const categoryItem = target.closest('.category-item');
                this.toggleCategory(categoryItem.dataset.id);
                return;
            }

            // 处理添加子分类按钮点击
            if (target.closest('.add-subcategory')) {
                e.stopPropagation();
                const categoryItem = target.closest('.category-item');
                this.createCategory(categoryItem.dataset.id);
                return;
            }

            // 处理删除分类按钮点击
            if (target.closest('.delete-category')) {
                e.stopPropagation();
                const categoryItem = target.closest('.category-item');
                this.deleteCategory(categoryItem.dataset.id);
                return;
            }

            // 处理重命名按钮点击
            if (target.closest('.rename-category')) {
                e.stopPropagation();
                const categoryItem = target.closest('.category-item');
                this.renameCategory(categoryItem.dataset.id);
                return;
            }

            // 处理分类选择
            const categoryItem = target.closest('.category-item');
            if (categoryItem) {
                this.selectCategory(categoryItem.dataset.id);
            }
        });
        
        // 笔记相关
        document.getElementById('addNote').addEventListener('click', () => this.createNote());
        document.getElementById('noteTitle').addEventListener('input', () => this.startAutoSave());
        document.getElementById('noteContent').addEventListener('input', () => this.startAutoSave());
        
        // 搜索相关
        document.getElementById('searchInput').addEventListener('input', (e) => this.handleSearch(e));

        // 添加保存按钮事件监听
        document.getElementById('saveNote').addEventListener('click', () => this.saveNote());

        // 初始化显示
        this.renderCategories();
        this.renderNotes();

        this.initDragAndDrop();
    }

    // 初始化拖拽功能
    initDragAndDrop() {
        // 为笔记列表添加拖拽事件
        document.getElementById('notesList').addEventListener('dragstart', (e) => {
            const noteItem = e.target.closest('li');
            if (noteItem) {
                this.draggedNoteId = parseInt(noteItem.dataset.id);
                e.dataTransfer.setData('text/plain', this.draggedNoteId);
                e.dataTransfer.effectAllowed = 'move';
                noteItem.classList.add('dragging');
            }
        });

        document.getElementById('notesList').addEventListener('dragend', (e) => {
            const noteItem = e.target.closest('li');
            if (noteItem) {
                noteItem.classList.remove('dragging');
            }
        });

        // 为分类列表添加拖放事件
        document.getElementById('categoryList').addEventListener('dragover', (e) => {
            e.preventDefault();
            const categoryItem = e.target.closest('.category-item');
            if (categoryItem) {
                e.dataTransfer.dropEffect = 'move';
                this.highlightDropTarget(categoryItem);
            }
        });

        document.getElementById('categoryList').addEventListener('dragleave', (e) => {
            const categoryItem = e.target.closest('.category-item');
            if (categoryItem) {
                this.removeDropHighlight(categoryItem);
            }
        });

        document.getElementById('categoryList').addEventListener('drop', (e) => {
            e.preventDefault();
            const categoryItem = e.target.closest('.category-item');
            if (categoryItem) {
                this.removeDropHighlight(categoryItem);
                const targetCategoryId = categoryItem.dataset.id;
                const level = parseInt(categoryItem.dataset.level);

                // 只允许拖放到一级或二级分类
                if (level <= 1) {
                    this.moveNoteToCategoryByDrag(this.draggedNoteId, targetCategoryId);
                } else {
                    this.showToast('只能移动到一级或二级分类', 'error');
                }
            }
        });
    }

    // 高亮显示可放置目标
    highlightDropTarget(categoryItem) {
        const level = parseInt(categoryItem.dataset.level);
        if (level <= 1) {
            categoryItem.classList.add('drop-target');
        }
    }

    // 移除高亮显示
    removeDropHighlight(categoryItem) {
        categoryItem.classList.remove('drop-target');
    }

    // 通过拖拽移动笔记
    moveNoteToCategoryByDrag(noteId, categoryId) {
        const notes = this.storage.getNotes();
        const noteIndex = notes.findIndex(note => note.id === noteId);
        
        if (noteIndex > -1) {
            notes[noteIndex] = {
                ...notes[noteIndex],
                categoryId: categoryId,
                updateTime: new Date().toISOString()
            };
            
            this.storage.saveNotes(notes);
            this.renderNotes();
            
            const categoryName = this.getCategoryNameById(categoryId);
            this.showToast(`笔记已移动到"${categoryName}"`);
        }
    }

    // 创建新笔记
    createNote() {
        // 确定笔记应该保存在哪个分类下
        let targetCategoryId = 'uncategorized';
        
        if (this.currentCategoryId !== 'all') {
            if (this.currentCategoryPath.length > 0) {
                // 获取路径中最后一个分类（当前选中的分类）
                const currentCategory = this.currentCategoryPath[this.currentCategoryPath.length - 1];
                // 如果是叶子节点（没有子分类）或是最后一级分类，则使用当前分类
                if (currentCategory.isLeaf) {
                    targetCategoryId = currentCategory.id;
                }
            }
        }

        const note = {
            id: Date.now(),
            title: '新建笔记',
            content: '',
            categoryId: targetCategoryId,
            createTime: new Date().toISOString(),
            updateTime: new Date().toISOString()
        };

        const notes = this.storage.getNotes();
        notes.push(note);
        this.storage.saveNotes(notes);
        
        // 显示创建成功提示，包含分类信息
        const categoryName = this.currentCategoryPath.length > 0 
            ? this.currentCategoryPath[this.currentCategoryPath.length - 1].name 
            : '未分类';
        this.showToast(`笔记已创建在 "${categoryName}" 分类下`);

        this.renderNotes();
        this.selectNote(note);
    }

    // 开始自动保存倒计时
    startAutoSave() {
        this.updateSaveStatus('编辑中...', 'saving');
        
        // 清除之前的定时器
        if (this.saveTimeout) {
            clearTimeout(this.saveTimeout);
        }
        
        // 设置新的定时器，1.5秒后自动保存
        this.saveTimeout = setTimeout(() => {
            this.saveNote();
        }, 1500);
    }

    // 保存笔记
    saveNote() {
        if (!this.currentNote) return;

        const titleInput = document.getElementById('noteTitle');
        const contentInput = document.getElementById('noteContent');
        const notes = this.storage.getNotes();
        
        try {
            const noteIndex = notes.findIndex(n => n.id === this.currentNote.id);
            if (noteIndex > -1) {
                notes[noteIndex] = {
                    ...notes[noteIndex],
                    title: titleInput.value,
                    content: contentInput.value,
                    updateTime: new Date().toISOString()
                };
                
                this.storage.saveNotes(notes);
                this.lastSaveTime = new Date();
                this.updateSaveStatus('已保存', 'saved');
                this.renderNotes();
            }
        } catch (error) {
            console.error('保存失败:', error);
            this.updateSaveStatus('保存失败', 'error');
        }
    }

    // 更新保存状态提示
    updateSaveStatus(message, status) {
        const saveStatus = document.getElementById('saveStatus');
        saveStatus.textContent = message;
        saveStatus.className = 'save-status ' + status;
        
        // 如果是"已保存"状态，2秒后清除提示
        if (status === 'saved') {
            setTimeout(() => {
                if (this.lastSaveTime && new Date() - this.lastSaveTime >= 2000) {
                    saveStatus.textContent = '';
                }
            }, 2000);
        }
    }

    // 渲染笔记列表
    renderNotes() {
        const notesList = document.getElementById('notesList');
        const notes = this.storage.getNotes();
        
        let filteredNotes;

        if (this.currentCategoryId === 'all') {
            filteredNotes = notes;
        } else {
            // 如果是叶子节点，只显示直接属于该分类的笔记
            const currentCategory = this.currentCategoryPath[this.currentCategoryPath.length - 1];
            if (currentCategory && currentCategory.isLeaf) {
                filteredNotes = notes.filter(note => note.categoryId === this.currentCategoryId);
            } else {
                // 如果不是叶子节点，显示所有子分类的笔记
                const childCategoryIds = this.getChildCategoryIds(this.currentCategoryId);
                filteredNotes = notes.filter(note => 
                    childCategoryIds.includes(note.categoryId) || 
                    note.categoryId === this.currentCategoryId
                );
            }
        }

        notesList.innerHTML = filteredNotes.map(note => `
            <li data-id="${note.id}" 
                class="${this.currentNote?.id === note.id ? 'active' : ''}"
                draggable="true">
                <div class="note-item">
                    <div class="note-info">
                        <div class="note-title">${note.title || '无标题'}</div>
                        <div class="note-time">${new Date(note.updateTime).toLocaleString()}</div>
                    </div>
                    <button class="btn-delete" data-id="${note.id}" title="删除笔记">
                        <i>🗑️</i>
                    </button>
                </div>
            </li>
        `).join('');

        // 添加点击事件
        notesList.querySelectorAll('li').forEach(li => {
            // 笔记选择事件
            li.addEventListener('click', (e) => {
                // 如果点击的是删除按钮，不触发选择事件
                if (e.target.closest('.btn-delete')) return;
                
                const noteId = parseInt(li.dataset.id);
                const note = notes.find(n => n.id === noteId);
                this.selectNote(note);
            });
        });

        // 添加删除按钮事件
        notesList.querySelectorAll('.btn-delete').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation(); // 阻止事件冒泡
                const noteId = parseInt(btn.dataset.id);
                this.deleteNote(noteId);
            });
        });
    }

    // 渲染分类列表
    renderCategories() {
        const categoryList = document.getElementById('categoryList');
        const categories = this.storage.getCategories();

        categoryList.innerHTML = this.generateCategoryHTML(categories);

        
        // 添加展开/折叠功能
        categoryList.querySelectorAll('.category-toggle').forEach(toggle => {
            toggle.addEventListener('click', (e) => {
                e.stopPropagation();
                const categoryItem = toggle.closest('li');
                console.log(categoryItem)
                categoryItem.classList.toggle('expanded');
            });
        });
    }

    // 生成分类HTML
    generateCategoryHTML(categories, level = 0) {
        return categories.map(category => {
            console.log(category)
            console.log(level)
            const hasChildren = category.children && category.children.length > 0;
            const isActive = this.currentCategoryId === category.id;
            const isExpanded = this.expandedCategories.has(category.id);
            
            return `
                <li class="category-item ${isActive ? 'active' : ''} ${isExpanded ? 'expanded' : ''}" 
                    data-id="${category.id}"
                    data-level="${level}">
                    <div class="category-content">
                        <span class="category-prefix">
                            ${hasChildren ? 
                                `<span class="category-toggle">
                                    <i class="toggle-icon">▶</i>
                                </span>` : 
                                '<span class="category-toggle-placeholder"></span>'
                            }
                        </span>
                        <span class="category-name">
                            <i class="category-icon">${category.isDefault ? '📑' : '📁'}</i>
                            ${category.name}
                        </span>
                        ${!category.isDefault ? `
                            <div class="category-actions">
                                ${level === 0 ? `
                                    <button class="btn-icon add-subcategory" title="添加子分类">
                                        <i>📁</i>
                                    </button>
                                ` : ''}
                                <button class="btn-icon rename-category" title="重命名">
                                    <i>✏️</i>
                                </button>
                                <button class="btn-icon delete-category" title="删除分类">
                                    <i>🗑️</i>
                                </button>
                            </div>
                        ` : ''}
                    </div>
                    ${hasChildren ? `
                        <div class="subcategories-wrapper">
                            <ul class="subcategories">
                                ${this.generateCategoryHTML(category.children, level + 1)}
                            </ul>
                        </div>
                    ` : ''}
                </li>
            `;
        }).join('');
    }

    // 创建新分类
    createCategory(parentId = null) {
        // 如果是创建子分类，先检查父分类的层级
        if (parentId) {
            const parentLevel = this.getCategoryLevel(parentId);
            if (parentLevel >= 1) { // 如果父分类已经是二级或更深，则不允许创建
                this.showToast('最多只能创建二级分类', 'error');
                return;
            }
        }

        const categoryName = prompt('请输入分类名称：');
        if (!categoryName) return;

        const categories = this.storage.getCategories();
        const newCategory = {
            id: 'category_' + Date.now(),
            name: categoryName,
            children: []
        };

        if (!parentId) {
            // 创建一级分类
            categories.push(newCategory);
        } else {
            // 创建二级分类
            const addToParent = (cats) => {
                for (let cat of cats) {
                    if (cat.id === parentId) {
                        if (!cat.children) cat.children = [];
                        cat.children.push(newCategory);
                        return true;
                    }
                    if (cat.children && addToParent(cat.children)) {
                        return true;
                    }
                }
                return false;
            };
            addToParent(categories);
        }

        this.storage.saveCategories(categories);
        this.renderCategories();
    }

    // 删除分类
    deleteCategory(categoryId) {
        const categories = this.storage.getCategories();
        
        const deleteFromCategories = (cats) => {
            for (let i = 0; i < cats.length; i++) {
                if (cats[i].id === categoryId) {
                    // 将该分类下的所有笔记移到"未分类"
                    const notes = this.storage.getNotes();
                    notes.forEach(note => {
                        if (note.categoryId === categoryId) {
                            note.categoryId = 'uncategorized';
                        }
                    });
                    this.storage.saveNotes(notes);
                    
                    // 删除分类
                    cats.splice(i, 1);
                    return true;
                }
                if (cats[i].children && deleteFromCategories(cats[i].children)) {
                    return true;
                }
            }
            return false;
        };

        deleteFromCategories(categories);
        this.storage.saveCategories(categories);
        this.renderCategories();
        this.renderNotes();
    }

    // 选择分类
    selectCategory(categoryId) {
        this.currentCategoryId = categoryId;
        this.currentCategoryPath = this.getCategoryPath(categoryId);
        
        // 确保父分类保持展开状态
        this.ensureParentCategoriesExpanded(categoryId);
        
        this.renderCategories();
        this.renderNotes();
    }

    // 获取分类的完整路径
    getCategoryPath(categoryId) {
        const categories = this.storage.getCategories();
        const path = [];

        const findPath = (cats, targetId) => {
            for (const cat of cats) {
                if (cat.id === targetId) {
                    path.push({
                        id: cat.id,
                        name: cat.name,
                        isLeaf: !cat.children || cat.children.length === 0
                    });
                    return true;
                }
                if (cat.children && cat.children.length > 0) {
                    if (findPath(cat.children, targetId)) {
                        path.unshift({
                            id: cat.id,
                            name: cat.name,
                            isLeaf: false
                        });
                        return true;
                    }
                }
            }
            return false;
        };

        if (categoryId !== 'all' && categoryId !== 'uncategorized') {
            findPath(categories, categoryId);
        } else {
            path.push({
                id: categoryId,
                name: categoryId === 'all' ? '全部笔记' : '未分类',
                isLeaf: true
            });
        }

        return path;
    }

    // 确保父分类保持展开
    ensureParentCategoriesExpanded(categoryId) {
        const categories = this.storage.getCategories();
        
        const findParentAndExpand = (cats, targetId) => {
            for (const cat of cats) {
                if (cat.children && cat.children.length > 0) {
                    if (cat.children.some(child => child.id === targetId)) {
                        this.expandedCategories.add(cat.id);
                        return true;
                    }
                    if (findParentAndExpand(cat.children, targetId)) {
                        this.expandedCategories.add(cat.id);
                        return true;
                    }
                }
            }
            return false;
        };

        findParentAndExpand(categories, categoryId);
    }

    // 搜索功能
    handleSearch(e) {
        const searchText = e.target.value.toLowerCase();
        const notesList = document.getElementById('notesList');
        const notes = this.storage.getNotes();

        // 过滤笔记
        const filteredNotes = notes.filter(note => {
            const matchesCategory = this.currentCategory === '全部笔记' || 
                                  note.category === this.currentCategory;
            const matchesSearch = note.title.toLowerCase().includes(searchText) || 
                                note.content.toLowerCase().includes(searchText);
            return matchesCategory && matchesSearch;
        });

        // 渲染搜索结果
        notesList.innerHTML = filteredNotes.map(note => `
            <li data-id="${note.id}" class="${this.currentNote?.id === note.id ? 'active' : ''}">
                <div class="note-title">${this.highlightSearchText(note.title, searchText)}</div>
                <div class="note-time">${new Date(note.updateTime).toLocaleString()}</div>
            </li>
        `).join('');
    }

    // 高亮搜索文本
    highlightSearchText(text, searchText) {
        if (!searchText) return text;
        const regex = new RegExp(`(${searchText})`, 'gi');
        return text.replace(regex, '<mark>$1</mark>');
    }

    // 选择笔记时更新状态
    selectNote(note) {
        this.currentNote = note;
        const titleInput = document.getElementById('noteTitle');
        const contentInput = document.getElementById('noteContent');
        const saveStatus = document.getElementById('saveStatus');
        
        if (note) {
            titleInput.value = note.title;
            contentInput.value = note.content;
            titleInput.disabled = false;
            contentInput.disabled = false;
            saveStatus.textContent = '';
        } else {
            titleInput.value = '';
            contentInput.value = '';
            titleInput.disabled = true;
            contentInput.disabled = true;
        }

        setHtml(note.content)
        
        this.renderNotes();
    }

    // 添加删除笔记的方法
    deleteNote(noteId) {
        if (!confirm('确定要删除这条笔记吗？此操作不可恢复。')) {
            return;
        }

        try {
            const notes = this.storage.getNotes();
            const noteIndex = notes.findIndex(note => note.id === noteId);
            
            if (noteIndex > -1) {
                // 如果删除的是当前选中的笔记，清除编辑区
                if (this.currentNote && this.currentNote.id === noteId) {
                    this.currentNote = null;
                    this.selectNote(null);
                }

                notes.splice(noteIndex, 1);
                this.storage.saveNotes(notes);
                this.renderNotes();
                
                // 显示删除成功提示
                this.showToast('笔记已删除');
            }
        } catch (error) {
            console.error('删除失败:', error);
            this.showToast('删除失败', 'error');
        }
    }

    // 添加提示消息方法
    showToast(message, type = 'success') {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        document.body.appendChild(toast);

        // 2秒后移除提示
        setTimeout(() => {
            toast.classList.add('toast-fade');
            setTimeout(() => toast.remove(), 300);
        }, 2000);
    }

    // 切换分类的展开/折叠状态
    toggleCategory(categoryId) {
        if (this.expandedCategories.has(categoryId)) {
            this.expandedCategories.delete(categoryId);
        } else {
            this.expandedCategories.add(categoryId);
        }
        this.renderCategories();
    }

    // 获取所有子分类ID
    getChildCategoryIds(categoryId) {
        const categories = this.storage.getCategories();
        const ids = [];

        const collectIds = (cats) => {
            for (const cat of cats) {
                if (cat.id === categoryId && cat.children) {
                    cat.children.forEach(child => {
                        ids.push(child.id);
                        if (child.children) {
                            collectIds(child.children);
                        }
                    });
                } else if (cat.children) {
                    collectIds(cat.children);
                }
            }
        };

        collectIds(categories);
        return ids;
    }

    // 获取分类的层级
    getCategoryLevel(categoryId) {
        const categories = this.storage.getCategories();
        
        const findLevel = (cats, targetId, currentLevel = 0) => {
            for (const cat of cats) {
                if (cat.id === targetId) {
                    return currentLevel;
                }
                if (cat.children) {
                    const level = findLevel(cat.children, targetId, currentLevel + 1);
                    if (level !== -1) {
                        return level;
                    }
                }
            }
            return -1;
        };

        return findLevel(categories, categoryId);
    }

    // 添加重命名分类的方法
    renameCategory(categoryId) {
        const categories = this.storage.getCategories();
        
        // 查找当前分类名称
        const findCurrentName = (cats) => {
            for (const cat of cats) {
                if (cat.id === categoryId) {
                    return cat.name;
                }
                if (cat.children) {
                    const name = findCurrentName(cat.children);
                    if (name) return name;
                }
            }
            return null;
        };

        const currentName = findCurrentName(categories);
        if (!currentName) return;

        // 弹出重命名对话框
        const newName = prompt('请输入新的分类名称：', currentName);
        if (!newName || newName === currentName) return;

        // 更新分类名称
        const updateName = (cats) => {
            for (let cat of cats) {
                if (cat.id === categoryId) {
                    cat.name = newName;
                    return true;
                }
                if (cat.children && updateName(cat.children)) {
                    return true;
                }
            }
            return false;
        };

        if (updateName(categories)) {
            this.storage.saveCategories(categories);
            this.renderCategories();
            this.showToast(`分类已重命名为"${newName}"`);
        }
    }
}



// 富文本编辑器逻辑
const { createEditor, createToolbar,E } = window.wangEditor
var htmlString = ""
// var btn = document.getElementById("save");
// btn.addEventListener("click", () => {
//     getHtmlString()z
// })
function getHtmlString(){
    window.java.onContentChange(htmlString)
}

const editorConfig = {
    placeholder: '输入文字....',
    MENU_CONF: {
      uploadImage: {
          base64LimitSize: 10 * 1024 * 1024
      }
    },
    onChange(editor) {
        const html = editor.getHtml()
        document.getElementById("noteContent").value = html
        htmlString = html;
    }
}

const editor = createEditor({
    selector: '#editor-container',
    html: '<p><br></p>',
    config: editorConfig,
    mode: 'default', // or 'simple'
})


const toolbarConfig = {}

const toolbar = createToolbar({
    editor,
    selector: '#toolbar-container',
    config: toolbarConfig,
    mode: 'default', // or 'simple'
})
function setHtml(html) {
    try {
        editor.select([])
        editor.deleteFragment()
        editor.dangerouslyInsertHtml(html)
    }catch (e) {
        alert(e)
    }
}
